package com.fowo.api.common.lang;


import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.io.IOException;

/**
 * 表示新建中 (NEW{Long}) 或 Long 混合主键类型
 */
@JsonSerialize(using = DataId.Serialize.class)
@JsonDeserialize(using = DataId.Deserialize.class)
public class DataId implements Comparable<DataId> {
    private final Long id;
    private final boolean _new;

    public DataId(Long id) {
        this._new = false;
        this.id = id;
    }

    public DataId(String id) {
        if (id.startsWith("NEW")) {
            this._new = true;
            this.id = Long.parseLong(id.substring(3));
        } else {
            this._new = false;
            this.id = Long.parseLong(id);
        }
    }

    public Long getId() {
        return id;
    }

    public boolean isNew() {
        return _new;
    }

    @Override
    public int compareTo(DataId dataId) {
        return dataId._new == _new ? id.compareTo(dataId.id) : (_new ? 1 : -1);
    }

    public static class Serialize extends JsonSerializer<DataId> {
        @Override
        public void serialize(DataId dataId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (dataId.isNew()) {
                jsonGenerator.writeString(String.format("NEW%d", dataId.id));
            }
            else {
                jsonGenerator.writeNumber(dataId.id);
            }
        }
    }

    public static class Deserialize extends JsonDeserializer<DataId> {

        @Override
        public DataId deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
            return new DataId(jsonParser.getValueAsString());
        }
    }
}
